#include "misc.h"

#include "core_cm3.h"

/*******************************************************************************
* Function Name  : delay_us
* Description    : This function delay n us.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void delay_us(unsigned int n)
{
    //get load
    unsigned int tLOAD;
    unsigned int told;
    unsigned int tnow;
    unsigned int delt_t;
    unsigned int tcnt;
    unsigned int ticks;
    tLOAD = SysTick->LOAD;
    told = SysTick->VAL;
    tcnt = 0;
    ticks = 9 * n;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
            {
                delt_t = told - tnow;
            }
            else
            {
                delt_t = tLOAD - (tnow - told);
            }
            tcnt += delt_t;
            told = tnow;
            if (tcnt >= ticks)
            {
                break;
            }
        }
    }
}
/*******************************************************************************
* Function Name  : delay_ms
* Description    : This function delay n ms.
* Input          : None
* Output         : None
* Return         : None
*******************************************************************************/
void delay_ms(unsigned int n)
{
    while (n--)
    {
        delay_us(1000);    //delay 1 ms
    }
}

